package ca.cbc.gis.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.HibernateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ca.cbc.giscommon.util.HibernateUtil;


public class GISFilter implements Filter {
	private static Logger logger = LoggerFactory.getLogger(GISFilter.class);

	public void init(FilterConfig filterConfig) throws ServletException {
		logger.info("------ LocalSrvExt Starting Up -------");
		HibernateUtil.createSessionFactory();
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		try {
			HibernateUtil.beginTransaction();
			HibernateUtil.getSession().setDefaultReadOnly(true);
			chain.doFilter(request,response);	
			HibernateUtil.commitTransaction();
		} catch (HibernateException e) {
			HibernateUtil.rollbackTransaction();
			logger.error("Hibernate Exception!", e);
		}
	}

	public void destroy() {
		logger.info("====== LocalSrvExt Shuting down =====");
		HibernateUtil.shutdown();
	}

}
